<!DOCTYPE html>
<html xmlns:panelHeight="http://www.w3.org/1999/xhtml">
<!--
创建了本模板作为物料管理/物料管理/物料管理的样板
需要更改的有路径 bumen dwuliao wuliaofenlei
需要更改的文本有 [物料类别 物料管理 物料名称 添加物料信息 保存并新增下一物料 新增物料类别
删除一级物料会同时一并删除其中二级物料,请谨慎操作]
需要更改的name有 projname

其中树形菜单中只设定二级,在二级下不能新建
可以鼠标右键操作树形菜单操作
当删除一级菜单会删除二级菜单并会删除对应的一级和二级下面的所有详细数据
新增数据窗口及搜索窗口都可以点到input后进行回车的方法调用

在详细列表中,通过左边树形菜单的选择,来实现一级下包括二级菜单内详细数据的展示
分别通过detail表[dwuliao,dwuliao,dwuliao]中的w_id(绑定二级菜单id),o_id(绑定一级菜单id)
来实现.
-->


<head>
    <meta charset="UTF-8">
    <title>物料管理</title>
    <link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.3.3/themes/default/easyui.css"></link>
    <link rel="stylesheet" type="text/css" href="/static/jquery-easyui-1.3.3/themes/icon.css"></link>
    <style type="text/css">

        #menu{
            list-style: none;
            margin: 0px;
            padding: 0px;
            position: absolute;
            display: none;
            width: 100px;
            height: 100px;
            background-color: white;
        }

        #menu li{
            margin: 0px;
            padding: 0px;
        }
    </style>
    <script type="text/javascript" src="/static/jquery-easyui-1.3.3/jquery.min.js"></script>
    <script type="text/javascript" src="/static/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/static/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
    <script src="/static/js/FileSaver.min.js"></script>
    <script src="/static/js/xlsx.full.min.js"></script>
    <!--<noscript><iframe src=*.html></iframe></noscript>-->
    <!--<script type="text/javascript">-->

    <!--//浏览器的默认行为：浏览器自带的功能，如：超链接，文本框可以输入内容，网页的右键菜单-->

    <!--//oncontextmenu:上下文菜单，就是右键菜单。-->

    <!--window.oncontextmenu = function(event){-->
    <!--// alert("hi");-->
    <!--var evt = event || window.event;-->
    <!--evt.preventDefault();-->
    <!--var clientWidth = document.documentElement.clientWidth || document.body.clientWidth ;-->
    <!--var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft;-->

    <!--var clientHeight = document.documentElement.clientHeight || document.body.clientHeight ;-->
    <!--var scrollTop = document.documentElement.scrollTop || document.body.scrollTop ;-->

    <!--//给left和top分别赋值为鼠标的位置；-->
    <!--$("menu").style.left = evt.pageX+"px";-->
    <!--$("menu").style.top = evt.pageY+"px";-->

    <!--//如果鼠标右边放不下菜单，就把left的值的改了-->
    <!--if(evt.pageX+100>clientWidth+scrollLeft){//菜单应该在鼠标左边；-->
    <!--var left1 = evt.pageX-100;-->
    <!--$("menu").style.left = left1+"px";-->
    <!--}-->

    <!--//如果鼠标下边放不下菜单，就把top的值的改了-->
    <!--if(evt.pageY+100>clientHeight+scrollTop){-->
    <!--var top1 = (evt.pageY-100);-->
    <!--$("menu").style.top = top1+"px";-->
    <!--}-->

    <!--$("menu").style.display = "block";-->
    <!--}-->

    <!--window.onmousedown = function(){-->
    <!--$("menu").style.display = "none";-->

    <!--}-->

    <!--function $(id){-->
    <!--return document.getElementById(id);-->
    <!--}-->

    <!--</script>-->
    <script type="text/javascript">

        var url;
        //禁止整体该页面的右键弹出html相关,不阻碍easyui右键
        $(function () {
            $(document).bind('contextmenu', function (e) {
                e.preventDefault();
                $('#tree-0').menu('show', {
                    left: e.pageX,
                    top: e.pageY
                });
            });
        });
        //物料类别模块管理
        $(document).ready(function () {
            loadTree();
            loadDataGrid();
            goodsUnitLoadDbClick();
            changeHuishouxiangStateBySelect();
        });

        function changeHuishouxiangStateBySelect(){

            $("#kehuishou").combobox({
                onChange:function(n,o){
                    if(n=="可回收"){
                        $("#huishouxiang").removeAttr("disabled");
                        $("#huishouxiang").removeAttr("readonly");
                    }else if(n=="不可回收"){
                        $("#huishouxiang").attr("disabled","disabled");
                        $("#huishouxiang").attr("readonly","readonly");
                        $("#huishouxiang").val("");
                    }else{
                        $("#huishouxiang").attr("readonly","readonly");
                        $("#huishouxiang").val("");
                    }
                }
            })
        }
        //重新加载tree类别 设定默认add按钮可见及功能 del按钮不可用
        function reloadTree(){
            $('#tree').tree('reload');

            $('#add').linkbutton('enable');
            $('#add').attr("href", "javascript:openTypeAddDialog()");
            $('#del').linkbutton('disable');
        }
        //加载tree类别
        function loadTree(){
            $("#tree").tree({
                url: '/admin/wuliaoTree/loadWuliaoTree',
                onLoadSuccess: function (node, data) {
                    $("#tree").tree('expandAll');
                },
                onDblClick:function(node){

                },
                //右键选择树形菜单操作
                onContextMenu: function (e, node) { //右键时触发事件                      
                    e.preventDefault(); //阻止浏览器捕获右键事件
                    var rootNodes = $("#tree").tree('getRoots');
                    for(var i=0;i<rootNodes.length;i++){
                        var theNode = $("#tree").tree('find',rootNodes[i].id);
                        $("#tree").tree('uncheck',theNode.target);
                    }
                    $("#tree").tree('select',node.target);
                    if(node.attributes.state == 2){
                        $("#tree-2").menu('show',{
                            left: e.pageX,//在鼠标点击处显示菜单
                            top: e.pageY
                        });
                    }else if(node.attributes.state == 1){
                        $("#tree-1").menu('show',{
                            left: e.pageX,//在鼠标点击处显示菜单
                            top: e.pageY
                        });
                    }else{
                        $('#tree-0').menu('show', {
                            left: e.pageX,//在鼠标点击处显示菜单
                            top: e.pageY
                        });
                    }

                },
                //单击某类别 展示不同详细和按钮选择
                onClick: function (node) {
                    if (node.attributes.state == 2) { // 假如是二级菜单,可以删除
                        $("#dg").datagrid('load',{
                            "w_id":node.id
                        })
                        $('#add').linkbutton('disable');
                        $('#del').linkbutton('enable');
                        $('#del').attr("href", "javascript:deleteType()");
                    } else if (node.attributes.state == 1) {
                        $("#dg").datagrid('load',{
                            "o_id":node.id
                        })
                        $('#add').linkbutton('enable');
                        $('#add').attr("href", "javascript:openTypeAddDialog()");
                        $('#del').linkbutton('enable');
                        $('#del').attr("href", "javascript:deleteType()");
                    }
                }
            });
        }
        //添加类别 如果树形菜单为外部不选择node节点 则先重载 取消node的选择 保存为一级菜单
        function openTypeAddDialog(treeSelect) {
            if(treeSelect==0){
                reloadTree();
            }
            $("#dlg").dialog("open").dialog("setTitle", "新增物料类别");
        }
        //保存类别 有则加冕 无则改之 有node则创建其二级菜单 没有node则创建一级菜单
        function saveType() {
            var typeName = $("#typeName").val();
            if (!$("#fm").form("validate")) {
                return;
            }
            var node = $('#tree').tree('getSelected'); // 获取选中节点
            var parentId; // 父节点Id
            if (node == null) {
                parentId = -1;
            } else {
                parentId = node.id;
            }

            $.post("/admin/wuliaoTree/save", {'wuliaofenlei': typeName, 'p_id': parentId}, function (result) {
                if (result.success) {
                    $('#tree').tree('reload');
                    closeTypeDialog();
                } else {
                    $.messager.alert("系统提示", "提交失败，请联系管理员！");
                }
            }, "json");
        }
        //删除类别
        function deleteType() {
            $.messager.confirm('删除提示', '删除一级物料会同时一并删除其中二级物料,请谨慎操作', function (r) {
                if (r) {
                    // exit action;
                    var node = $('#tree').tree('getSelected'); // 获取选中节点
                    var id = node.id;
                    $.post("/admin/wuliaoTree/delete", {id: id}, function (result) {  //TODO 删除物料名称路径
                        if (result.success) {
                            $('#tree').tree('reload');
                            $("#dg").datagrid('reload');
                        } else {
                            $.messager.alert("系统提示", "提交失败，请联系管理员！");
                        }
                        $('#del').linkbutton('disable');
                    }, "json");
                }
            });

        }
        //关闭类别新增窗口
        function closeTypeDialog() {
            $("#dlg").dialog("close");
            $("#typeName").val("");
        }
        //搜索详细
        function searchDetails() {
            $("#dg").datagrid('load', {
                "mingchengguige": $("#s_name").val()
            });
        }
        //
        // function formatPurchasingPrice(val, row) {
        //     return "￥" + val;
        // }
        //
        // function formatSellingPrice(val, row) {
        //     return "￥" + val;
        // }
        function loadDataGrid(){
            //首先datagrid
            $("#dg").datagrid({

                //之后onLoadSuccess加载这两种方法
                //悬停提示tooltip
                onLoadSuccess: function (data) {
                    $(this).datagrid('tooltip');
                    $(this).datagrid('fixRownumber');
                },

                //双击事件
                onDblClickRow: function (index, row) {
                    $("#dlg2").dialog("open").dialog("setTitle", "修改信息");
                    $("#fm2").form("load", row);
                    $("#name").val(row.wuliaofenlei);
                    url = "/admin/dwuliao/update?id=" + row.id;
                    $("#saveAndAddNextBuuton").hide();
                    $("#saveDetails").hide();
                    $("#updateDetails").show();
                },
                onRowContextMenu: function (e, rowIndex, rowData) { //右键时触发事件                      
                    e.preventDefault(); //阻止浏览器捕获右键事件
                    $(this).datagrid("clearSelections"); //取消所有选中项
                    $(this).datagrid("selectRow", rowIndex); //根据索引选中该行
                    $('#grid-data').menu('show', {
                        left: e.pageX,//在鼠标点击处显示菜单
                        top: e.pageY
                    });
                    e.preventDefault();  //阻止浏览器自带的右键菜单弹出
                },
            }),
                //之下为鼠标悬停table上展示单个字段的tooltip
                $.extend($.fn.datagrid.methods, {
                    tooltip: function (jq, fields) {
                        return jq.each(function () {
                            var panel = $(this).datagrid('getPanel');
                            if (fields && typeof fields == 'object' && fields.sort) {
                                $.each(fields, function () {
                                    var field = this;
                                    bindEvent($('.datagrid-body td[field=' + field + '] .datagrid-cell', panel));
                                });
                            } else {
                                bindEvent($(".datagrid-body .datagrid-cell", panel));
                            }
                        });

                        function bindEvent(jqs) {
                            jqs.mouseover(function () {
                                var content = $(this).text();
                                if (content && content != "") {
                                    $(this).tooltip({
                                        content: content,
                                        trackMouse: true,
                                        deltaX: 15,
                                        deltaY: -5,
                                        onShow: function () {
                                            $(this).tooltip('tip').css({
                                                backgroundColor: '#f7f5d1',
                                                borderColor: 'black'
                                            });
                                        }
                                    }).tooltip('show');
                                }
                            });
                        }
                    }
                });

            $.extend($.fn.datagrid.methods, {
                fixRownumber : function (jq) {
                    return jq.each(function () {
                        var panel = $(this).datagrid("getPanel");
                        //获取最后一行的number容器,并拷贝一份
                        var clone = $(".datagrid-cell-rownumber", panel).last().clone();
                        //由于在某些浏览器里面,是不支持获取隐藏元素的宽度,所以取巧一下
                        clone.css({
                            "position" : "absolute",
                            left : -1000
                        }).appendTo("body");
                        var width = clone.width("auto").width();
                        //默认宽度是25,所以只有大于25的时候才进行fix
                        if (width > 25) {
                            //多加5个像素,保持一点边距
                            $(".datagrid-header-rownumber,.datagrid-cell-rownumber", panel).width(width + 5);
                            //修改了宽度之后,需要对容器进行重新计算,所以调用resize
                            $(this).datagrid("resize");
                            //一些清理工作
                            clone.remove();
                            clone = null;
                        } else {
                            //还原成默认状态
                            $(".datagrid-header-rownumber,.datagrid-cell-rownumber", panel).removeAttr("style");
                        }
                    });
                }
            });




            //在datagrid中进行调用data-options="" 写上代码
            //onLoadSuccess : function(data) {
            //$(this).datagrid('fixRownumber');
            //}
        }
        //物料单位的双击事件
        function goodsUnitLoadDbClick(){
            $("#dg4").datagrid({
                //双击事件
                onDblClickRow: function (index, row) {
                    var selectedRows=$("#dg4").datagrid("getSelections");
                    var name=selectedRows[0].danwei;
                    $("#danwei").combobox("reload");
                    $("#danwei").combobox("setValue",name);
                    $("#dlg4").dialog("close");
                }
            });
        }

        function importExcel(){

        }

        //根据类别创建详细
        function openDetailAddDialog() {
            var node = $('#tree').tree('getSelected'); // 获取选中节点
            if (!node) {
                $.messager.alert("系统提示", "请选择物料分类进行创建！");
            } else {
                resetDetailValue();
                $("#dlg2").dialog("open").dialog("setTitle", "添加物料信息");
            }
            url = "/admin/dwuliao/save";
            $("#updateDetails").hide();
            $("#saveAndAddNextBuuton").show();
            $("#saveDetails").show();
        }
        //修改详细
        function openDetailsModifyDialog() {
            var selectedRows = $("#dg").datagrid("getSelections");
            if (selectedRows.length != 1) {
                $.messager.alert("系统提示", "请选择一条要修改的数据！");
                return;
            }
            var row = selectedRows[0];
            $("#dlg2").dialog("open").dialog("setTitle", "修改信息");
            $("#fm2").form("load", row);
            $("#name").val(row.wuliaofenlei);
            url = "/admin/dwuliao/update?id=" + row.id;
            $("#saveAndAddNextBuuton").hide();
            $("#saveDetails").hide();
            $("#updateDetails").show();
        }
        //保存详细
        function saveDetails(type) {
            if (!$("#fm2").form("validate")) {
                return;
            }
            console.log("danwei:"+$("#danwei").combobox("getValue"));
            console.log("save dwuliao");
            var node = $('#tree').tree('getSelected'); // 获取选中节点
            console.log("node.id:"+node.id);
            var parent = $('#tree').tree('getParent',node.target);//父节点
            console.log("parent:"+parent);
            var nodeId = node.id;
            var parentId;
            if(parent){
                parentId = parent.id;
            }else{
                parentId = node.id; //一级菜单下没有父菜单,则使用其自身的id
            }
            console.log("saveDetails parentId:"+parentId);
            $.post(url, {
                "dalei":$("#dalei").val(),
                "wuliaobianma":$("#wuliaobianma").val(),
                "mingchengguige": $("#mingchengguige").val(),
                "danwei": $("#danwei").combobox("getValue"),
                "kehuishou": $("#kehuishou").combobox("getValue"),
                "huishouxiang": $("#huishouxiang").val(),
                "beizhu": $("#beizhu").val(),
                "founder": $("#founder").val(),
                "w_id":nodeId,
                'o_id':parentId
            }, function (result) {
                if (result.success) {
                    if (type == 1) {
                        $("#dlg2").dialog("close");
                    }
                    $("#dg").datagrid('reload');
                    $.messager.alert("系统提示", "保存成功！");
                } else {
                    $.messager.alert("系统提示", "保存失败,请重试！");
                }
            });
        }
        //更改详细
        function updateDetails() {
            console.log("update dwuliao");
            $.post(url, {
                "dalei":$("#dalei").val(),
                "wuliaobianma":$("#wuliaobianma").val(),
                "mingchengguige": $("#mingchengguige").val(),
                "danwei": $("#danwei").combobox("getValue"),
                "kehuishou": $("#kehuishou").combobox("getValue"),
                "huishouxiang": $("#huishouxiang").val(),
                "beizhu": $("#beizhu").val(),
                "founder": $("#founder").val(),
                // "w_id":nodeId,
                // 'o_id':parentId
            }, function (result) {
                if (result.success) {
                    $("#dlg2").dialog("close");
                    $("#dg").datagrid('reload');
                    $.messager.alert("系统提示", "更改成功！");

                } else {
                    $.messager.alert("系统提示", "更改失败,请重试！");
                }
            });
        }
        //key=13时判定同一窗口是更新还是保存
        function saveOrUpdate(){
            var updateBtnIsShow = $("#updateDetails").is(":visible");

            if (updateBtnIsShow){
                return updateDetails();
            }else{
                return saveDetails(2);
            }
        }
        //关闭详细窗口
        function closeDetailsDialog() {
            $("#dlg2").dialog("close");
            resetTypeValue();
        }
        //重置数据
        function resetDetailValue(){
            $("#fm2").form('clear');
        }
        function resetTypeValue() {
            // $("#typeId").val("");
            $("#typeName").val("");
            // $("#name").val("");
            // $("#model").val("");
            // $('#purchasingPrice').numberbox('setValue', "");
            // $('#sellingPrice').numberbox('setValue', "");
            // $('#minNum').numberbox('setValue', "");
            // $("#producer").val("");
            // $("#remarks").val("");
        }
        //删除详细
        function deleteDetails() {
            var selectedRows = $("#dg").datagrid("getSelections");
            if (selectedRows.length == 0) {
                $.messager.alert("系统提示", "请选择要删除的数据！");
                return;
            }
            var ids = new Array();
            if(selectedRows.length>1){
                for(var i=0;i<selectedRows.length;i++){
                    ids.push(selectedRows[i].id);
                }
            }else if(selectedRows.length==1){
                var id = selectedRows[0].id;
                ids.push(id);
            }
            $.messager.confirm("系统提示", "您确定要删除这条数据吗？", function (r) {
                if (r) {
                    $.post("/admin/dwuliao/delete", {'ids': ids}, function (result) {
                        if (result.success) {
                            $.messager.alert("系统提示", "数据已成功删除！");
                            $("#dg").datagrid("reload");
                        } else {
                            $.messager.alert("系统提示", "<font color=red>" + result.errorInfo + "</font>");
                        }
                    }, "json");
                }
            });
        }
        //物料单位选择弹出窗
        function openChooseGoodsUnitDialog(){
            $("#dlg4").dialog("open").dialog("setTitle","单位");
        }
        //物料单位添加弹出窗
        function openGoodsUnitAddDialog(){
            $("#dlg5").dialog("open").dialog("setTitle","添加单位信息");
        }
        //删除物料单位
        function deleteGoodsUnit(){
            var selectedRows=$("#dg4").datagrid("getSelections");
            if(selectedRows.length!=1){
                $.messager.alert("系统提示","请选择要删除的数据！");
                return;
            }
            var id=selectedRows[0].id;
            $.messager.confirm("系统提示","您确定要删除这条数据吗？",function(r){
                if(r){
                    $.post("/admin/wuliaodanwei/delete",{id:id},function(result){
                        if(result.success){
                            $("#dg4").datagrid("reload");
                        }else{
                            $.messager.alert("系统提示",result.errorInfo);
                        }
                    },"json");
                }
            });
        }
        //选择物料单位
        function chooseGoodsUnit(){
            var selectedRows=$("#dg4").datagrid("getSelections");
            if(selectedRows.length!=1){
                $.messager.alert("系统提示","请选择单位！");
                return;
            }
            var name=selectedRows[0].danwei;
            $("#danwei").combobox("reload");
            $("#danwei").combobox("setValue",name);
            $("#dlg4").dialog("close");
        }
        //关闭物料单位选择窗
        function closeGoodsUnitDialog(){
            $("#dlg4").dialog("close");
        }
        //保存物料单位
        function saveGoodsUnit(){
            $("#fm5").form("submit",{
                url:"/admin/wuliaodanwei/save",
                onSubmit:function(){
                    return $(this).form("validate");
                },
                success:function(result){
                    var result=eval('('+result+')');
                    if(result.success){
                        $.messager.alert("系统提示","保存成功！");
                        closeGoodsUnitAddDialog();
                        $("#dg4").datagrid("reload");
                    }else{
                        $.messager.alert("系统提示",result.errorInfo);
                    }
                }
            });
        }
        //关闭物料单位添加窗
        function closeGoodsUnitAddDialog(){
            $("#dlg5").dialog("close");
            $("#wuliaodanwei").val("");
        }

    </script>

</head>
<body class="easyui-layout" style="padding-top: 2px">
<!--类别展示-->
<div id="tree-panel" data-options="region:'west',collapsible:false" style="width:200px" title="物料类别" split=true>
    <!--添加分类树形菜单的过长滚动条-->
    <div style="overflow-x: auto; overflow-y: auto; height: 90%; width:98%;">
        <ul id="tree" class="easyui-tree" style="padding: 10px"></ul>
    </div>
    <div style="position:absolute;bottom: 10px;left: 15px">
        <a id="add" href="javascript:openTypeAddDialog()" class="easyui-linkbutton" data-options="iconCls:'icon-add'">新增</a>
        <a id="del" href="javascript:deleteType()" class="easyui-linkbutton"
           data-options="iconCls:'icon-remove',disabled:true">删除</a>
    </div>
</div>
<!--详细展示-->
<div data-options="region:'center'">
    <table id="dg" title="物料管理" class="easyui-datagrid"  loadMsg="加载数据中,请稍候."
           fitColumns="true" pagination="true" rownumbers="true" checkbox="true" pageList=[10,20,30,40,50,1000000]
           url="/admin/dwuliao/getSelective" fit="true" toolbar="#tb">
        <thead>
        <tr>
            <th field="ukyo" align="center" width="30" checkbox="true"></th>
            <th field="id" width="60" align="center" sortable="true" hidden="hidden">编号</th>
            <th field="dalei" width="65" align="center" sortable="true">大类</th>
            <th field="wuliaobianma" width="90" align="center" sortable="true">物料编码</th>
            <th field="mingchengguige" width="130" align="center" sortable="true">名称规格</th>
            <th field="danwei" width="50" align="center" sortable="true">单位</th>
            <th field="kehuishou" width="30" align="center" sortable="true">可回收</th>
            <th field="huishouxiang" width="40" align="center" sortable="true">回收项</th>
            <th field="beizhu" width="130" align="center" sortable="true">备注</th>
            <th field="founder" width="80" align="center" sortable="true">创建人</th>
            <th field="createtime" width="50" align="center" sortable="true">创建时间</th>
            <!--<th field="w_id" width="20" align="center">外键</th>-->
            <!--<th field="typeId" width="40" align="center" formatter="formatGoodsTypeId" hidden=true>类别ID</th>-->
        </tr>
        </thead>
    </table>
    <div id="tb">
        <div>
            <a href="javascript:openDetailAddDialog()" class="easyui-linkbutton" iconCls="icon-add" plain="true">添加</a>
            <a href="javascript:uploadidalogonline()" class="easyui-linkbutton" iconCls="icon-add" plain="true">批量导入</a>
            <a href="javascript:openDetailsModifyDialog()" class="easyui-linkbutton" iconCls="icon-edit"
               plain="true">修改</a>
            <a href="javascript:deleteDetails()" class="easyui-linkbutton" iconCls="icon-remove" plain="true">删除</a>
            <!--<a href="javascript:exportExcel()" class="easyui-linkbutton" iconCls="icon-save" plain="true">选中导出</a>-->
            <a href="javascript:void(0)" id="export_excel" iconCls="icon-save" class="easyui-linkbutton"
               plain="true">保存数据</a>
        </div>
        <div>
            &nbsp;名称规格：&nbsp;<input type="text" id="s_name" size="20" onkeydown="if(event.keyCode==13)searchDetails()"/>
            <a href="javascript:searchDetails()" class="easyui-linkbutton" iconCls="icon-search" plain="true">搜索</a>
        </div>
    </div>
</div>
<!--类别弹出窗及按钮组-->
<div id="dlg" class="easyui-dialog" style="width:300px;height:120px;padding: 10px 20px"
     closed="true" buttons="#dlg-buttons" data-options="onClose:function(){$('#typeName').val('');}">

    <form id="fm" onkeydown="if(event.keyCode==13)saveType()">
        <div>
            物料类别：&nbsp;<input type="text" id="typeName" name="name" class="easyui-validatebox" required="true"/>
        </div>
    </form>
</div>
<div id="dlg-buttons">
    <a href="javascript:saveType()" class="easyui-linkbutton" iconCls="icon-ok">保存</a>
    <a href="javascript:closeTypeDialog()" class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
</div>

<!--大屏幕上右键datagrid dlg-->
  <div id="grid-data" class="easyui-menu" style="width: 80px; display: none;">
    <div id="grid-data-edit" href="javascript:openDetailsModifyDialog()" data-options="iconCls:'icon-edit'">修改</div>
    <div id="grid-data-delete" href="javascript:deleteDetails()" data-options="iconCls:'icon-remove'" plain="true">删除</div>
</div>
<!--二级菜单右键弹出-->
  <div id="tree-2" class="easyui-menu" style="width: 80px; display: none;">
    <div id="tree-2-delete" href="javascript:deleteType()" data-options="iconCls:'icon-remove'" >删除二级菜单</div>
</div>
<!--一级菜单右键弹出-->
  <div id="tree-1" class="easyui-menu" style="width: 80px; display: none;">
    <div id="tree-1-add-2" href="javascript:openTypeAddDialog()" data-options="iconCls:'icon-add'" >添加二级菜单</div>
    <div id="tree-1-delete" href="javascript:deleteType()" data-options="iconCls:'icon-remove'" >删除一级菜单</div>
</div>
<!--树形菜单右键弹出-->
  <div id="tree-0" class="easyui-menu" style="width: 80px; display: none;">
    <div id="tree-0-add-1" href="javascript:openTypeAddDialog(0)" data-options="iconCls:'icon-add'" >添加一级菜单</div>
    <div id="tree-0-refresh" href="javascript:reloadTree()" data-options="iconCls:'icon-reload'" >重新加载类别</div>
</div>
         
<div id="dlg2" class="easyui-dialog" style="width:550px;height:365px;padding: 5px 5px"
     closed="true" buttons="#dlg-buttons2" data-options="onClose:function(){resetTypeValue()}">
    <fieldset style="border-color: #E7F0FF">
        <legend>物料信息</legend>
        <form id="fm2" onkeydown="if(event.keyCode==13)saveOrUpdate()">
            <table cellspacing="8px">
                <tr>
                    <td width="60">大类：</td>
                    <td>
                        <input type="text" id="dalei" name="dalei" class="easyui-validatebox"  size="10" />
                    </td>
                    <td width="80">物料编码：</td>
                    <td><input type="text" id="wuliaobianma" name="wuliaobianma" class="easyui-validatebox"  size="15"  /></td>
                </tr>
                <tr>
                    <td width="80">名称规格：</td>
                    <td colspan="4">
                        <input type="text" id="mingchengguige" name="mingchengguige" class="easyui-validatebox" required="true" size="20" />
                    </td>
                </tr>
                <tr>
                    <td width="80">单位：</td>
                    <td>
                        <!--<input type="text" id="danwei" name="danwei" class="easyui-validatebox" required="true" size="10"  />-->
                        <select class="easyui-combobox" required="true" id="danwei" name="danwei"  style="width: 80px;" editable="true"
                                data-options="panelHeight:'auto',editable:false,valueField:'danwei',textField:'danwei',url:'/admin/wuliaodanwei/comboList'">
                        </select>
                        <a href="javascript:openChooseGoodsUnitDialog()" class="easyui-linkbutton" iconCls="icon-search"  plain="true"></a>
                    </td>
                </tr>
                <tr>
                    <td width="60">可回收：</td>
                    <td>
                        <select id="kehuishou" class="easyui-combobox" name="kehuishou" editable="false" required="true" panelHeight="auto" panelMaxHeight="200px" style="width:80px;">
                            <option value="不可回收">不可回收</option>
                            <option value="可回收">可回收</option>
                        </select>
                        <!--<input type="text" id="kehuishou" name="kehuishou" class="easyui-validatebox" required="true" size="10" />-->
                    </td>
                    <td width="60">回收项：</td>
                    <td><input type="text" id="huishouxiang" name="huishouxiang" class="easyui-validatebox" size="10" readonly="readonly"/></td>
                </tr>
                <tr>
                    <td width="60">备注：</td>
                    <td>
                        <input type="text" id="beizhu" name="beizhu" class="easyui-validatebox" size="10" />
                    </td>
                </tr>
            </table>
        </form>
    </fieldset>
</div>

<div id="dlg-buttons2">
    <a id="saveAndAddNextBuuton" href="javascript:saveDetails(2)" class="easyui-linkbutton"
       iconCls="icon-ok">保存并新增下一物料</a>
    <a id="saveDetails" href="javascript:saveDetails(1)" class="easyui-linkbutton" iconCls="icon-ok">保存</a>
    <a id="updateDetails" href="javascript:updateDetails()" class="easyui-linkbutton" iconCls="icon-ok">更改</a>
    <a href="javascript:closeDetailsDialog()" class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
</div>

<!--TODO 应用到生成单据的树形展示-->
<div id="dlg3" class="easyui-dialog" style="width:180px;height:300px;padding: 10px 10px"
     closed="true" buttons="#dlg-buttons3">

    <ul id="typeTree" class="easyui-tree"></ul>
</div>
<!--TODO 应用到生成单据的树形展示-->
<div id="dlg-buttons3">
    <a href="javascript:saveGoodsTypeChoose()" class="easyui-linkbutton" iconCls="icon-ok" plain="true">选择</a>
    <a href="javascript:closeGoodsTypeChooseDialog()" class="easyui-linkbutton" iconCls="icon-cancel"
       plain="true">关闭</a>
</div>

<div id="dlg4" class="easyui-dialog" style="width:200px;height:300px;"
     closed="true">

    <table id="dg4"  class="easyui-datagrid" rownumbers="true" singleSelect="true"
           url="/admin/wuliaodanwei/listAll" fitColumns="true" fit="true" toolbar="#tb2">
        <thead>
        <tr>
            <th field="id" width="100" align="center" hidden=true>单位ID</th>
            <th field="danwei" width="100" align="center">单位名称</th>
        </tr>
        </thead>
    </table>
    <div id="tb2">
        <div>
            <a href="javascript:openGoodsUnitAddDialog()" class="easyui-linkbutton"  plain="true">添加</a>
            <a href="javascript:deleteGoodsUnit()" class="easyui-linkbutton"  plain="true">删除</a>
            <a href="javascript:chooseGoodsUnit()" class="easyui-linkbutton"  plain="true">确定</a>
            <a href="javascript:closeGoodsUnitDialog()" class="easyui-linkbutton"  plain="true">取消</a>
        </div>
    </div>

</div>

<div id="dlg5" class="easyui-dialog" style="width:300px;height:120px;padding: 10px 20px"
     closed="true" buttons="#dlg-buttons5"  data-options="onClose:function(){$('#wuliaodanwei').val('');}">

    <form id="fm5" method="post">
        <div>
            物料单位：&nbsp;<input type="text" id="wuliaodanwei" name="danwei" class="easyui-validatebox" required="true"/>
        </div>

    </form>
</div>

<div id="dlg-buttons5">
    <a href="javascript:saveGoodsUnit()" class="easyui-linkbutton" iconCls="icon-ok">保存</a>
    <a href="javascript:closeGoodsUnitAddDialog()" class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
</div>
       
<!--上传excel的弹出窗-->
<div id="uploadonlineinfo" class="easyui-window" style="width:380px;padding:10px 40px" closed="true">

    <form id="fam" method="post" enctype="multipart/form-data">

        <!--<input class="easyui-filebox" id="onlinefilename" name="onlinefilename" data-options="prompt:'文件上传'"-->
        <!--style="width:100%" />-->
        <input type="file"
               id="uploadfile" name="uploadfile" style="width:100%"/>
    </form>
    <br>

    <div data-options="region:'south',border:false" style="text-align:center;padding:5px 0 0;">
        <button id="uploadBtn" class="easyui-b" data-options="iconCls:'icon-ok'"
                style="width:80px">上传
        </button>
    </div>
    <br>
    <p style="text-align: center"><a href="/static/xlsx/wuliaomoban1.xlsx">下载物料表excel模板</a></p>

</div>
<!--<ul id="menu">-->
<!--<li>鱼香肉丝</li>-->
<!--<li>醋溜土豆丝</li>-->
<!--<li>麻辣小龙虾</li>-->
<!--<li>回锅肉</li>-->
<!--</ul>-->

<div id="exportexcelinfo" class="easyui-window" style="width:380px;padding:10px 40px" closed="true">

    <form id="oil"  enctype="multipart/form-data">

        <!--<input class="easyui-filebox" id="onlinefilename" name="onlinefilename" data-options="prompt:'文件上传'"-->
        <!--style="width:100%" />-->
        导出excel名称:
        <input type="text"
               id="downloadExcelName" name="downloadExcelName" style="width:100%"/>
    </form>
    <br>

    <div data-options="region:'south',border:false" style="text-align:center;padding:5px 0 0;">
        <!--<button id="exportBtn" class="easyui-linkbutton" data-options="iconCls:'icon-ok'"-->
        <button id="exportBtn" class="easyui-linkbutton" style="width:80px">导出选中
        </button>
        <button id="exportTypeBtn" class="easyui-linkbutton"  style="width:80px">导出类别
            <!--<button id="exportTypeBtn" class="easyui-linkbutton" data-options="iconCls:'icon-ok'"-->

        </button>
    </div>
    <br>

</div>

</body>
<script>

    /* 上传excel的窗口打开操作 */
    function uploadidalogonline() {
        var node = $('#tree').tree('getSelected'); // 获取选中节点
        if(node==undefined){
            $.messager.alert("系统提示","请选中物料类别！");
            return;
        }
        $('#uploadonlineinfo').window('open').dialog('setTitle', '文件上传');
    }

    // 上传文件
    $("#uploadBtn").click(uploadonline);

    // 上传操作
    function uploadonline() {
        var node = $('#tree').tree('getSelected'); // 获取选中节点
        if(node==undefined){
            $.messager.alert("系统提示","请选中物料类别！");
            return;
        }
        console.log("node.id:"+node.id);
        var parent = $('#tree').tree('getParent',node.target);//父节点
        console.log("parent:"+parent);
        var w_id = node.id;
        var o_id;
        if(parent){
            o_id = parent.id;
        }else{
            o_id = node.id; //一级菜单下没有父菜单,则使用其自身的id
        }

        console.log("uploadonline");
        // var add = '/excel/importExcel';
        var theExcel = $("#uploadfile")[0].files[0];
        console.log(theExcel);
        var formData = new FormData();
        formData.append("theExcel", theExcel);
        console.log(formData);
        // if ("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != "") {
        $.ajax({
            url: '/excel/importExcel/wuliao/'+w_id+'/'+o_id,
            type: 'POST',
            data: formData,
            async: false,
            cache: false,
            contentType: false, //不设置内容类型
            processData: false, //不处理数据
            success: function (data) {
                if(data>0){
                    $.messager.alert("系统提示","操作成功！");
                    //成功导入,新增数据到wuliaokucunrizhi 去重 同时根据w_id,o_id 查

                    $("#dg").datagrid('reload');
                    $("#uploadonlineinfo").dialog("close");
                }else{
                    $.messager.alert("系统提示","操作失败！");
                    $("#dg").datagrid('reload');
                    $("#uploadonlineinfo").dialog("close");
                }
            }
        });
    }
    //
    // function wuliaoToRizhi(w_id,o_id){
    //     $.ajax({
    //         url: '/admin/wuliaorizhi//' + w_id + '/' + o_id,
    //         type: 'POST',
    //         success: function (data) {
    //
    //         }
    //     });
    // }

    // function exportExcel(){
    //
    // }

    //导出excel
    function exportExcel() {
        var node = $('#tree').tree('getSelected'); // 获取选中节点
        if(node==undefined){
            $.messager.alert("系统提示","请选中物料类别！");
            return;
        }
        // var node = $('#tree').tree('getSelected'); // 获取选中节点
        // var selectedRows = $("#dg").datagrid("getSelections");
        // if (selectedRows.length == 0) {
        //     $.messager.alert("系统提示", "请选择要导出的数据！");
        //     return;
        // }
        $('#exportexcelinfo').window('open').dialog('setTitle', '数据导出');
    }

    $("#exportTypeBtn").click(exportExcelByType);

    function exportExcelByType(){
        var node = $('#tree').tree('getSelected'); // 获取选中节点
        if(node==undefined){
            $.messager.alert("系统提示","请选中物料类别！");
            return;
        }
        if($("#downloadExcelName").val().length==0){
            $.messager.alert("系统提示", "请设定要导出的excel文件名！");
            return;
        }
        console.log("node.id:"+node.id);
        var parent = $('#tree').tree('getParent',node.target);//父节点
        console.log("parent:"+parent);
        var w_id = node.id;
        var o_id;
        if(parent){
            o_id = parent.id;
        }else{
            o_id = node.id; //一级菜单下没有父菜单,则使用其自身的id
        }
        $.ajax({
            url: '/excel/exportTypeExcel/wuliaoType',
            type: 'POST',
            data: {'downloadExcelName':$("#downloadExcelName").val(),'w_id':w_id,'o_id':o_id},
            success: function (data) {
                if(data>0){
                    $.messager.alert("系统提示","操作成功！");
                    $("#dg").datagrid('reload');
                    $("#uploadonlineinfo").dialog("close");
                }else{
                    $.messager.alert("系统提示","操作失败！");
                    $("#dg").datagrid('reload');
                    $("#uploadonlineinfo").dialog("close");
                }
            }
        });

    }


    // 导出文件byId
    $("#exportBtn").click(exportExcelByIds);

    function exportExcelByIds(){
        var node = $('#tree').tree('getSelected'); // 获取选中节点
        var selectedRows = $("#dg").datagrid("getSelections");
        if (selectedRows.length == 0) {
            $.messager.alert("系统提示", "请选择要导出的数据！");
            return;
        }
        if($("#downloadExcelName").val().length==0){
            $.messager.alert("系统提示", "请设定要导出的excel文件名！");
            return;
        }

        var ids = new Array();
        if(selectedRows.length>1){
            for(var i=0;i<selectedRows.length;i++){
                ids.push(selectedRows[i].id);
            }
        }else if(selectedRows.length==1){
            var id = selectedRows[0].id;
            ids.push(id);
        }
        $.ajax({
            url: '/excel/exportExcel/wuliao',
            type: 'POST',
            data: {'downloadExcelName':$("#downloadExcelName").val(),'ids':ids},
            success: function (data) {
                if(data>0){
                    $.messager.alert("系统提示","操作成功！");
                    $("#dg").datagrid('reload');
                    $("#uploadonlineinfo").dialog("close");
                }else{
                    $.messager.alert("系统提示","操作失败！");
                    $("#dg").datagrid('reload');
                    $("#uploadonlineinfo").dialog("close");
                }
            }
        });
    }


</script>
<script>
    // 导出excel按钮
    $("#export_excel").click(exportExcel);

    // 导出excel
    function exportExcel() {
        //获得选中记录 多选
        var row = $('#dg').datagrid('getRows');
        // var row = $('#dg').datagrid('getSelections');
        // 去除不需要导出的实体字段
        var deleteKey = ['updatetime','p_id','state',
            'w_id','o_id','sort','order'
        ];
        for (var i in row) {
            for (var j in deleteKey) {
                delete row[i][deleteKey[j]];
            }
        }
        if (row) {
            $.messager.confirm('确认按钮', '你确定要导出本页物料数据?', function (r) {
                if (r) {
                    downloadExl(row);
                }
            })
        }
    }

    function downloadExl(data, type) {
        var keys = Object.keys(data[0]);
        var firstRow = {};
        keys.forEach(function (item) {
            console.log("item:" + item);
            firstRow[item] = item;
        });
        data.unshift(firstRow);

        var content = {};

        //把json格式的数据转换为excel的行列形式
        var sheetsData = data.map(function (item, rowIndex) {
            return keys.map(function (key, columnIndex) {
                return Object.assign({}, {
                    value: item[key],
                    position: (columnIndex > 25 ? getCharCol(columnIndex) : String.fromCharCode(65 + columnIndex)) + (rowIndex + 1),
                });
            });
        }).reduce(function (prev, next) {
            return prev.concat(next);
        });

        sheetsData.forEach(function (item, index) {
            // content[item.position] = {v: item.value};
            if (item.value == 'id') {
                content[item.position] = {v: '序列号'};
            } else if (item.value == 'dalei') {
                content[item.position] = {v: '大类'};
            } else if (item.value == 'wuliaobianma') {
                content[item.position] = {v: '物料编码'};
            } else if (item.value == 'mingchengguige') {
                content[item.position] = {v: '名称规格'};
            } else if (item.value == 'danwei') {
                content[item.position] = {v: '单位'};
            } else if (item.value == 'kehuishou') {
                content[item.position] = {v: '可回收'};
            } else if (item.value == 'huishouxiang') {
                content[item.position] = {v: '回收项'};
            } else if (item.value == 'beizhu') {
                content[item.position] = {v: '备注'};
            } else if (item.value == 'founder') {
                content[item.position] = {v: '创建人'};
            } else if (item.value == 'createtime') {
                content[item.position] = {v: '创建时间'};
            } else {
                if (item.value == null || item.value == undefined || item.value == 'null') {
                    content[item.position] = {v: ''};  //remember
                } else {
                    content[item.position] = {v: item.value};  //remember
                }
            }
        });

        //设置区域,比如表格从A1到D10,SheetNames:标题
        var coordinate = Object.keys(content);
        var workBook = {
            SheetNames: ["1"],
            Sheets: {
                "1": Object.assign({}, content, {"!ref": coordinate[0] + ":" + coordinate[coordinate.length - 1]}),
            }
        };

        //这里的数据是用来定义导出的格式类型
        var excelData = XLSX.write(workBook, {bookType: "xlsx", bookSST: false, type: "binary"});
        var blob = new Blob([string2ArrayBuffer(excelData)], {type: ""});

        // filename = "石油焦";
        $.messager.prompt("输入框", "请输入保存文件名.", function (filename) {
            if (filename) {
                var nowTime = new Date().toLocaleDateString();
                saveAs(blob, filename + "-物料" + nowTime + ".xlsx"); //文件名
            }
        });
    }

    //字符串转字符流
    function string2ArrayBuffer(s) {
        var buf = new ArrayBuffer(s.length);
        var view = new Uint8Array(buf);
        for (var i = 0; i != s.length; ++i) {
            view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
    }

    //将指定的自然数转换为26进制表示. 映射关系: [0-25] -> [A-Z]
    function getCharCol(n) {
        var temCol = "",
            s = "",
            m = 0;
        while (n > 0) {
            m = n % 26 + 1;
            s = String.fromCharCode(m + 64) + s;
            n = (n - m) / 26;
        }
        return s;
    }

</script>
</html>